//
//  PushViewController.swift
//  BBAnimatedTransitioningDemo
//
//  Created by YouMao on 2022/4/28.
//

import UIKit
import BBAnimatedTransitioning

class PushViewController: UIViewController {

    let animator = BBTransitiontingAnimator()
    
    let interaction = UIPercentDrivenInteractiveTransition()
    
    let imageView = UIImageView(frame: CGRect(x: 40, y: 100, width: 192, height: 108))
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    init() {
        super.init(nibName: nil, bundle: nil)
        self.modalPresentationStyle = .custom
        self.transitioningDelegate = animator
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Push"
        view.backgroundColor = .gray
        let pan = UIPanGestureRecognizer(target: self, action: #selector(pan(_:)))
        view.addGestureRecognizer(pan)
        
        imageView.isUserInteractionEnabled = true
        imageView.image = UIImage(named: "th")
        view.addSubview(imageView)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))
        imageView.addGestureRecognizer(tap)
    }

    deinit {
        print(self)
    }
}

extension PushViewController {
    
    @objc func tap(_ gesture: UITapGestureRecognizer) {
        let vc = ImageViewController()
        self.present(vc, animated: true)
    }
    
    @objc func pan(_ gesture: UIPanGestureRecognizer) {
        switch gesture.state {
        case .began:
            animator.outInteraction = interaction
            self.navigationController?.popViewController(animated: true)
            break
        case .changed:
            let offset = gesture.translation(in: view)
            if offset.x > 0 && offset.x < 300 {
                interaction.update(offset.x / 300.0)
            }
            break
        case .cancelled:
            interaction.cancel()
            animator.outInteraction = nil
            break
        case .ended:
            if interaction.percentComplete > 0.5 {
                interaction.finish()
            } else {
                interaction.cancel()
                animator.outInteraction = nil
            }
            break
        default:
            break
        }
        
    }
}
